package com.yourenbang.lingyun.transaction.util.hjtx;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import java.util.TreeMap;

/**
 * com.icardpay.front.test
 * ott-test
 *
 * @EMAIL:SHENGMIAO@HKRT.CN
 * @Description: <br/>
 * Date         Author        Version        Discription
 * -----------------------------------------------------------------------------------
 * 2017/8/8     xuezheng          1.0             1.0
 */
public class Sha256 {
	
	public static Logger log = LoggerFactory.getLogger(Sha256.class);
//    public static String signBySha256(Object obj,String key) {
//        Map<String, String> objectAsMap;
//        try {
//            objectAsMap = BeanUtils.describe(obj);
//            objectAsMap.remove("class");
//            return signBySha256(objectAsMap,key);
//        } catch (Exception e) {
//            throw new RuntimeException("bean convert map fail", e);
//        }
//    }

    public static String signBySha256(Map<String, Object> objectAsMap,String key) {
        String result = sortStringByMap(objectAsMap) + "key=" +key ;
        log.debug("signBySha256 result : "+result);
        String sign = DigestUtils.sha256Hex(result).toUpperCase();
        return sign;
    }

    /**
     * 使用 Map按key进行排序
     * @param map
     * @return
     */
    public static Map<String, Object> sortMapByKey(Map<String, Object> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }

        Map<String, Object> sortMap = new TreeMap<String, Object>(
                new MapKeyComparator());

        sortMap.putAll(map);

        return sortMap;
    }
    /**
     * 将Map存储的对象，转换为key=value&key=value&的字符,并将key按顺序排序
     */
    public static String sortStringByMap(Map<String, Object> map){
        ArrayList<String> list = new ArrayList<String>();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
//            if (entry.getValue() != null && String.valueOf(entry.getValue()).length() > 0) {
                list.add(entry.getKey() + "=" + entry.getValue() + "&");
//            }
        }
        int size = list.size();
        String[] arrayToSort = list.toArray(new String[size]);
        Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < size; i++) {
            sb.append(arrayToSort[i]);
        }
        return sb.toString();
    }
}
